<template>
  <el-dialog
    :title="title"
    center
    :visible="open"
    :modal="open"
    @close="close()"
    width="90%"
  >
    <div class="vue-flowchart-editor-container">
      <flowchart-editor
        :read-only="readOnly"
        :key="reRender"
        :chart-data="flowChartData"
        :chart-data-node-items="flowChartNodeItems"
        :showRightInfo="true"
        @save-data="save"
        @reload="reload"
      />
    </div>
  </el-dialog>
</template>
<script>
import FlowchartEditor from "@/flow/workflow/flowchartEditor";
import chartData from "@/flow/workflow/data";
import dataNodeItems from "@/flow/workflow/dataNodeItems";
import cloneDeep from "lodash/cloneDeep";
import "@/flow/workflow/iconfont";
import {
  getWorkflowJson,
  updateWorkflowJson,
} from "@/api/batch_app/workflowConfig";
export default {
  name: "EditNode",
  components: {
    FlowchartEditor,
  },
  props: {
    // 是否只读模式
    readOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      title: this.$t("common.edit"),
      open: false,
      id: "",
      flowCode: "",
      reRender: +new Date(),
      flowChartData: {},
      flowChartNodeItems: dataNodeItems,
    };
  },
  mounted() {
    this.$on("toggle-read-only", () => {
      this.readOnly = !this.readOnly;
      this.$nextTick(() => {
        this.reRender = +new Date(); // 重新渲染组件
      });
    });
    this.flowChartData = {};
  },
  methods: {
    show(id, code) {
      this.id = id;
      this.flowCode = code;
      if (id) {
        getWorkflowJson(this.id).then((res) => {
          if (res.result && res.result != "[]") {
            //console.log('加载远程数据')
            this.flowChartData = JSON.parse(res.result);
            this.reload(this.flowChartData);
            console.log("this.flowChartDataaaaaaaa", this.flowChartData);
          } else {
            let initData = JSON.parse(JSON.stringify(chartData));
            //console.log('本地数据初始化',initData)
            // 重置数据e
            this.reload(initData);
            this.$set(
              this.flowChartData.nodes[0],
              "nodeCode",
              `${this.flowCode}_START`
            );
          }
        });
      }

      this.open = true;
    },
    save(data) {
      // 在这里写数据保存逻辑
      console.log("data", data);
      this.flowChartData = cloneDeep(data);
      let postData = {
        flowId: this.id,
        flowCode: this.flowCode,
        editorData: JSON.stringify(data),
      };
      updateWorkflowJson(postData).then((res) => {
        this.msgSuccess(this.$t("common.operateSuccess"));
        this.close();
      });
    },
    reload(json) {
      this.flowChartData = json;
      this.reRender = +new Date(); // 重新渲染组件
    },
    // 取消按钮
    close() {
      this.$emit("changeTypeInfoOpen", false);
      this.open = false;
    },
  },
};
</script>

<style>
</style>
